<?php

declare(strict_types=1);

namespace App\Pay\Job;

use App\Activity\Model\ActivityGoodsModel;
use App\Order\Service\OrderGoodsService;
use App\Pay\Service\PayService;
use App\Resource\Model\GoodsListModel;
use Hyperf\AsyncQueue\Job;
use Hyperf\Utils\ApplicationContext;

class PaidJob extends Job
{

    private $orderNo;

    public function __construct($orderNo)
    {
        $this->orderNo = $orderNo;
    }

    public function handle()
    {
        $container = ApplicationContext::getContainer();
        $orderNo = $this->orderNo;
        try {
            // 商品列表
            $field = ['goods_id','group_id','number','activity_goods_id'];
            $goodsArr = $container->get(OrderGoodsService::class)->getOrderGoodsList(['order_no' => $orderNo], $field);
            // 0、普通商品 1、小跑好物拼团  2、会员专区 3、限时抢购 4、秒杀 5、免单
            foreach ($goodsArr as $k => $v) {
                if ($v['group_id'] == 0) {
                    $goods = GoodsListModel::query()->where(['goods_id' => $v['goods_id']])->first();
                    $goods->number_sales = $goods->number_sales + $v['number'];
                    $goods->number_stock = $goods->number_stock - $v['number'];
                    $goods->save();
                }
                if (in_array($v['group_id'], [1,4])) {
                    $goods = ActivityGoodsModel::query()->find($v['activity_goods_id']);
                    $goods->spell_num = $goods->spell_num + $v['number'];
                    $goods->stock = $goods->stock - $v['number'];
                    $goods->save();
                }
                if ($v['group_id'] == 3) {
                    $goods = ActivityGoodsModel::query()->find($v['activity_goods_id']);
                    $goods->spell_num = $goods->spell_num + $v['number'];
                    $goods->save();
                    $list = GoodsListModel::query()->where(['goods_id' => $v['goods_id']])->first();
                    $list->number_stock = $list->number_stock - $v['number'];
                    $list->save();
                }
                if ($v['group_id'] == 5) {
                    $goods = ActivityGoodsModel::query()->find($v['activity_goods_id']);
                    $goods->stock = $goods->stock - $v['number'];
                    $goods->spell_num = $goods->spell_num + $v['number'];
                    $goods->save();
                }
                //预留次日达减库存
            }
        }catch (\Exception $e){
            $param = [
                'order_no' => $orderNo,
                'number' => array_column($goodsArr, 'number', 'goods_id'),
                'group_id' => array_column($goodsArr, 'group_id', 'goods_id')
            ];
            $content = [
                'error' => '销量库存数量变更异常',
                'errMsg' => $e->getMessage()
            ];
            $container->get(PayService::class)->writeLog('error', $param , $content);
        }
    }
}
